package permission

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminUserPasswordResetLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminUserPasswordResetLogic - 用户重设密码
func NewAdminUserPasswordResetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserPasswordResetLogic {
	return &AdminUserPasswordResetLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminUserPasswordResetLogic) AdminUserPasswordReset(req *types.AdminUserPasswordReset) error {
	userDao := permission.NewAdminUserDao(l.ctx, l.svcCtx)

	// 查询用户
	adminUserCond := make([]predicate.AdminUser, 0, 2)
	adminUserCond = append(adminUserCond, adminuser.AdminUserUsernameEQ(req.AdminUserPhone))
	adminUserCond = append(adminUserCond, adminuser.IsDeleteEQ(bizadmin.NotDelete))
	adminUser, err := userDao.AdminUserFirst(adminUserCond)
	if err != nil {
		if ent.IsNotFound(err) {
			return xerr.ErrCodeMsg(xerr.ServerAdminUserNotExist, "用户不存在")
		}
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("用户不存在：%v", err.Error()))
	}

	// 校验用户
	if adminUser.AdminUserStatus == bizadmin.StatusDisable {
		return xerr.ErrCodeMsg(xerr.ServerAdminAccountBanned, "用户已被禁用")
	}

	// 从redis校验验证码
	err = handleCheckCaptchaFromRedis(l.svcCtx.BizRedis, l.ctx, constant.HzAdminLoginCaptchaKey+req.AdminUserPhone, req.AdminUserCaptcha)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerAdminSMSCodeError, fmt.Sprintf("验证码校验失败，%v", err.Error()))
	}

	// 校验密码是否一致
	if req.AdminUserPassword != "" && req.AdminUserPassword != req.AdminUserCheckPassword {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, "两次密码不一致")
	}

	// 新密码
	newPassword, err := common.HashPassword(req.AdminUserPassword)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("密码加密失败，%v", err.Error()))
	}

	// 更新密码
	adminUser.AdminUserPassword = newPassword
	err = userDao.AdminUserUpdate(adminUser, nil)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("更新密码失败，%v", err.Error()))
	}

	return nil
}
